package com.zkk.dao.impl;

import com.zkk.dao.JdbcCardDao;
import com.zkk.pojo.Card;
import com.zkk.pojo.TransferAccount;
import com.zkk.service.CardService;
import com.zkk.service.TransferAccountService;
import com.zkk.service.impl.CardServiceImpl;
import com.zkk.service.impl.TransferAccountServiceImpl;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class JdbcCardDaoImpl implements JdbcCardDao {
    @Override
    public int transferMoney(BigDecimal outPutMoney, String id_card, Connection connection) {
        int i ;
        try {
            CardService cardService = new CardServiceImpl();
            Card card = new Card();
            card.setId_card(id_card);
            BigDecimal bigDecimal = cardService.queryMoney(card);
            //得到被减去后的余额
            BigDecimal subtract = bigDecimal.subtract(outPutMoney);
            PreparedStatement preparedStatement = null;
            String sql = "update card set balance = ? where id_card = ?";
             preparedStatement = connection.prepareStatement(sql);
             preparedStatement.setBigDecimal(1,subtract);
             preparedStatement.setString(2,id_card);
             i = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return i;
    }

    @Override
    public int inTransferMoney(BigDecimal inPutMoney, String card_no, Connection connection) {
        int i;
        try {
            TransferAccountService transferMoney = new TransferAccountServiceImpl();
            TransferAccount transferAccount1 = transferMoney.queryByCard_no(card_no);
            BigDecimal property = transferAccount1.getProperty();
            //把查询到的余额和转账的钱相加，更新到账户中去
            BigDecimal add = property.add(inPutMoney);
            PreparedStatement preparedStatement = null;
            String sql = "update transferAccount set property = ? where card_no = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setBigDecimal(1,add);
            preparedStatement.setString(2,card_no);
             i = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return i;
    }
}
